require "basecamp"
require "rexml/document"

include REXML

Basecamp.establish_connection!(ARGV[0], ARGV[1], ARGV[2], true)

fetch_milestones = ARGV[3]
fetch_todos = ARGV[4]

people = {}

doc = Document.new("<lists />")
lists_element = doc.root

basecamp = Basecamp.new

projects = nil

begin
	projects = Basecamp::Project.find(:all)
rescue
	Basecamp.establish_connection!(ARGV[0], ARGV[1], ARGV[2], false)
	basecamp = Basecamp.new

	projects = Basecamp::Project.find(:all)
end

# projects = Basecamp::Project.find(:all)

projects.each do |project|
	lists_element.attributes["name"] = project.name

	list_element = lists_element.add_element("list")
	list_element.attributes["name"] = project.name + " Milestones"

	if (fetch_milestones == "yes")
		basecamp.milestones(project.id).each do |item|
			task_element = list_element.add_element("task")
			
			item.attributes.each do |key|
				if (key == "id")
					task_element.attributes[key] = "basecamp:" + item[key].to_s
				else
					task_element.attributes[key] = item[key].to_s
				end
			end
		end
	end
	
	if (fetch_todos == "yes")
		Basecamp::TodoList.all(project.id).each do |list|
			list_element = lists_element.add_element("list")
			list_element.attributes["name"] = list.name
		
			begin
				list.todo_items.each do |item|
					task_element = list_element.add_element("task")
			
					item.attributes.each do |key|
						if (key[0] == "id")
							task_element.attributes[key[0]] = "basecamp:" + key[1].to_s
						else
							task_element.attributes[key[0]] = key[1].to_s
						end
					end
				end
			rescue

			end
		end
	end
end

doc.write($stdout, 1)
